package com.ksyun.campus.dataserver.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import jakarta.annotation.PreDestroy;

/**
 * ZooKeeper配置类
 * 为DataServer提供CuratorFramework Bean
 */
@Slf4j
@Configuration
public class ZooKeeperConfig {

    @Value("${dataserver.zookeeper.connect-string:${minfs.zookeeper.connection-string:localhost:2181}}")
    private String zkConnectString;
    
    @Value("${dataserver.zookeeper.session-timeout:${minfs.zookeeper.session-timeout:30000}}")
    private int sessionTimeout;
    
    @Value("${dataserver.zookeeper.connection-timeout:${minfs.zookeeper.connection-timeout:15000}}")
    private int connectionTimeout;
    
    @Value("${dataserver.zookeeper.retry.base-sleep-time:${minfs.zookeeper.retry.base-sleep-time:1000}}")
    private int baseSleepTime;
    
    @Value("${dataserver.zookeeper.retry.max-retries:${minfs.zookeeper.retry.max-retries:3}}")
    private int maxRetries;
    
    private CuratorFramework curatorFramework;
    
    /**
     * 创建CuratorFramework Bean
     */
    @Bean
    public CuratorFramework curatorFramework() {
        log.info("Creating CuratorFramework with connection string: {}", zkConnectString);
        
        // 创建重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTime, maxRetries);
        
        // 创建CuratorFramework实例
        curatorFramework = CuratorFrameworkFactory.newClient(
                zkConnectString,
                sessionTimeout,
                connectionTimeout,
                retryPolicy
        );
        
        // 启动连接
        curatorFramework.start();
        
        try {
            // 等待连接建立
            curatorFramework.blockUntilConnected();
            log.info("CuratorFramework connected successfully");
        } catch (InterruptedException e) {
            log.error("Failed to connect to ZooKeeper", e);
            Thread.currentThread().interrupt();
            throw new RuntimeException("Failed to connect to ZooKeeper", e);
        }
        
        return curatorFramework;
    }
    
    /**
     * 应用关闭时清理资源
     */
    @PreDestroy
    public void cleanup() {
        if (curatorFramework != null) {
            log.info("Closing CuratorFramework connection");
            curatorFramework.close();
        }
    }
}